package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.entity.User;
import com.example.service.IdGeneratorService;
import com.example.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/users")
public class UserController {

    @Resource
    private UserService userService;
    
    @Resource
    private IdGeneratorService idGeneratorService;

    /**
     * 创建用户
     */
    @PostMapping
    public Map<String, Object> save(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 手动设置ID
            Long id = idGeneratorService.nextId();
            user.setId(id);
            
            log.info("准备插入用户，ID: {}, 用户名: {}", id, user.getUsername());
            
            boolean success = userService.save(user);
            
            log.info("插入结果: {}, 用户ID: {}", success, user.getId());
            
            // 验证插入是否成功
            if (success) {
                User savedUser = userService.getById(id);
                if (savedUser != null) {
                    log.info("验证成功：用户已保存到数据库，ID: {}", savedUser.getId());
                    result.put("verified", true);
                } else {
                    log.warn("警告：保存返回成功但无法查询到用户，ID: {}", id);
                    result.put("verified", false);
                }
            }
            
            result.put("success", success);
            result.put("data", user);
        } catch (Exception e) {
            log.error("保存用户时发生异常", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        return result;
    }

    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    public Map<String, Object> getById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            log.info("查询用户，ID: {}", id);
            User user = userService.getById(id);
            log.info("查询结果: {}", user != null ? "找到用户" : "未找到用户");
            
            result.put("success", true);
            result.put("data", user);
        } catch (Exception e) {
            log.error("查询用户时发生异常，ID: {}", id, e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        return result;
    }

    /**
     * 查询所有用户
     */
    @GetMapping
    public Map<String, Object> list() {
        Map<String, Object> result = new HashMap<>();
        try {
            log.info("查询所有用户");
            List<User> users = userService.list();
            log.info("查询到用户数量: {}", users.size());
            
            result.put("success", true);
            result.put("data", users);
            result.put("count", users.size());
        } catch (Exception e) {
            log.error("查询所有用户时发生异常", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        return result;
    }

    /**
     * 条件查询示例
     */
    @GetMapping("/search")
    public Map<String, Object> search(@RequestParam(required = false) String username,
                                    @RequestParam(required = false) Integer minAge,
                                    @RequestParam(required = false) Integer maxAge) {
        Map<String, Object> result = new HashMap<>();
        
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        // 根据用户名模糊查询
        if (username != null && !username.isEmpty()) {
            queryWrapper.like(User::getUsername, username);
        }
        // 年龄范围查询
        if (minAge != null) {
            queryWrapper.ge(User::getAge, minAge);
        }
        if (maxAge != null) {
            queryWrapper.le(User::getAge, maxAge);
        }
        
        List<User> users = userService.list(queryWrapper);
        result.put("success", true);
        result.put("data", users);
        return result;
    }

    /**
     * 批量保存示例
     */
    @PostMapping("/batch")
    public Map<String, Object> saveBatch(@RequestBody List<User> users) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 为每个用户设置ID
            for (User user : users) {
                user.setId(idGeneratorService.nextId());
            }
            
            log.info("准备批量插入用户，数量: {}", users.size());
            boolean success = userService.saveBatch(users);
            log.info("批量插入结果: {}", success);
            
            result.put("success", success);
            result.put("data", users);
        } catch (Exception e) {
            log.error("批量保存用户时发生异常", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        return result;
    }
} 